package 线程;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:谢君臣
 * @Date:2021/10/26-8:20
 * @version:1.0
 * @function:
 */
public class 秒杀 {
    public static void main(String[] args) throws InterruptedException, NoSuchFieldException, IllegalAccessException {
        Solution solution = new Solution(5);
        CountDownLatch count = new CountDownLatch(1);
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 2; i++) {
            String name = String.valueOf(i);
            executorService.submit(()->{
                try {
                    count.await();
                    solution.addOrder();
                } catch (InterruptedException | NoSuchFieldException e) {
                    e.printStackTrace();
                }
            },name);
            count.countDown();
        }
    }
    static class Solution{
        private Unsafe unsafe;
        private volatile int count;
        public Solution(int count) throws NoSuchFieldException, IllegalAccessException {
            this.count = count;
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            this.unsafe = (Unsafe) theUnsafe.get(null);
        }

        public void addOrder() throws NoSuchFieldException {
            ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
            threadLocal.set(0);
            int num = count;
            while (num>0&&threadLocal.get()<3){
                // 获取锁
                if (unsafe.compareAndSwapInt(count,unsafe.objectFieldOffset(Solution.class.getDeclaredField("count")),num,num-1)) {
                    System.out.println(Thread.currentThread().getName()+"：下单成功！"+num);
                    return;
                }
                // 失败重试
                threadLocal.set(threadLocal.get()+1);
            }
            System.out.println(Thread.currentThread().getName()+"：抢完了！");
        }
    }
}
